package org.example.seata.bs.auth.handler.check;

import cn.hutool.core.collection.CollUtil;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author hzq
 * @date 2021/12/10 14:27
 */
@Component
public class CheckAuthHandlerChain {

    private final List<CheckAuthHandler> checkAuthHandlers;

    public CheckAuthHandlerChain(@Nullable List<CheckAuthHandler> checkAuthHandlers) {
        this.checkAuthHandlers = CollUtil.isNotEmpty(checkAuthHandlers) ? checkAuthHandlers : Collections.emptyList();
    }

    /**
     * 检验
     *
     * @param principal   标识
     * @param credentials 凭证
     * @param checkType   检验类型
     */
    public void check(String principal, String credentials, String checkType) {

        for (CheckAuthHandler checkAuthHandler : checkAuthHandlers) {
            if (checkAuthHandler.supportType(checkType)) {
                checkAuthHandler.check(principal, credentials);
                return;
            }
        }

        throw new BadCredentialsException("验证码有误");
    }
}
